import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:orginone/components/XDialogs/XDialog.dart';
import 'package:orginone/components/XDialogs/dialog_utils.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/FileWidget/FileListWidget/components/FileTaskListWidget/components/FileinfoWidget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/target/base/team.dart';
import 'package:orginone/dart/core/thing/directory.dart';
import 'package:orginone/dart/core/thing/systemfile.dart';
import 'package:orginone/components/EntityWidget/common_fun.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/routers/router_const.dart';

import '../../../../XTextField/XTextField.dart';

bool hasAuth(dynamic data) {
  bool res = false;
  if (data is ISession) {
    data = data.target;
  }
  if (data is ITeam && data.hasRelationAuth() && data.id != data.userId) {
    res = true;
  }
  return res;
}

class FileTaskListWidget extends StatefulWidget {
  IDirectory iDirectory;
  FileTaskListWidget({Key? key, required this.iDirectory}) : super(key: key);

  @override
  State<FileTaskListWidget> createState() => _FileTaskListState();
}

class _FileTaskListState extends State<FileTaskListWidget> {
  late RxList<TaskModel> listTask = <TaskModel>[].obs;
  late IDirectory iDirectory;
  String taskKey = "taskEmitterKey";

  @override
  void initState() {
    iDirectory = widget.iDirectory;
    listTask.value = iDirectory.taskList;
    taskKey = iDirectory.subscribe((key, p1) {
      listTask.value = iDirectory.taskList;
    }, false);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Material(
          color: Colors.transparent,
          child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
              ),
              padding: const EdgeInsets.all(16),
              width: UIConfig.screenWidth - 32,
              height: UIConfig.screenHeight * 0.6,
              child: Column(
                children: [
                  Text(
                    "操作记录",
                    style:
                        TextStyle(fontSize: 24.sp, fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(height: 8),
                  listTask.isEmpty
                      ? const Expanded(child: Center(child: Text('')))
                      : Obx(() => Column(
                          children: listTask.value.reversed
                              .map((item) => Container(
                                    padding:
                                        EdgeInsets.symmetric(vertical: 16.h),
                                    width: UIConfig.screenWidth,
                                    decoration: const BoxDecoration(
                                        border: Border(
                                            bottom: BorderSide(
                                                width: 0.5,
                                                color:
                                                    XColors.dividerLineColor))),
                                    child: Row(
                                      children: [
                                        XImage.localImage(XImage.file,
                                            width: 30.w),
                                        const SizedBox(width: 4),
                                        Expanded(
                                            child: Text(
                                          item.name,
                                          overflow: TextOverflow.ellipsis,
                                          maxLines: 1,
                                          style: const TextStyle(fontSize: 16),
                                        )),
                                        item.finished >= 0
                                            ? Text(doubleToPercentage(
                                                (item.finished / 100)
                                                    .toDouble()))
                                            : GestureDetector(
                                                onTap: () {
                                                  // iDirectory.createFile(item.name);
                                                },
                                                child: const Text(
                                                  "上传失败",
                                                  style: TextStyle(
                                                      color: Colors.red),
                                                ),
                                              ),
                                      ],
                                    ),
                                  ))
                              .toList()))
                ],
              ))),
    );
  }
}

fileOperationModal(BuildContext context, {dynamic fileItem, dynamic data}) {
  return AlertDialogUtils.buildBottomModal(
      context,
      [
        if (hasAuth(data))
          ActionModel(
              title: fileItem is IDirectory ? "标记删除" : "彻底删除",
              onTap: () async {
                RoutePages.back(context);
                showDialog(
                    context: context,
                    builder: (context) => Center(
                          child: Material(
                              color: Colors.transparent,
                              child:
                                  buildConfirmDialogCommon(context, () async {
                                //删除文件
                                bool result = false;
                                if (fileItem is IDirectory) {
                                  IDirectory iDirectory = fileItem;
                                  result =
                                      await iDirectory.delete(notity: true);
                                } else if (fileItem is SysFileInfo) {
                                  result =
                                      await fileItem.hardDelete(notity: true);
                                }
                                if (!result) {
                                  ToastUtils.showMsg(msg: "删除失败，请稍后再试");
                                } else {
                                  RoutePages.back(context);
                                }
                                // command.emitterFlag("refreshFilePage");
                              })),
                        ),
                    barrierColor: Colors.black.withOpacity(0.6));
              }),
        if (fileItem is SysFileInfo)
          ActionModel(
              title: "下载文件",
              onTap: () async {
                RoutePages.to(
                    context: context,
                    path: Routers.messageFile,
                    data: {"file": fileItem.shareInfo()});
              }),
        ActionModel(
            title: "详细信息",
            onTap: () async {
              // Get.dialog(
              //     Center(
              //       child: Material(
              //           color: Colors.transparent,
              //           child: FileinfoModal(
              //             data: fileItem,
              //           )),
              //     ),
              //     barrierColor: Colors.black.withOpacity(0.6));
              RoutePages.to(
                  context: context,
                  child: Center(
                    child: Material(
                        color: Colors.transparent,
                        child: FileinfoWidget(
                          data: fileItem,
                        )),
                  ));
            })
      ],
      isNeedPop: false);
}

typedef CreateDirectoryCallBack = Function(
    String name, String code, String remark);

Future<void> showCreateDirectoryDialog(BuildContext context,
    {CreateDirectoryCallBack? onCreate,
    String name = '',
    String code = '',
    String remark = '',
    bool isEdit = false}) async {
  TextEditingController nameCrl = TextEditingController(text: name);
  TextEditingController codeCrl = TextEditingController(text: code);
  TextEditingController remarkCrl = TextEditingController(text: remark);
  nameCrl.addListener(() {
    String pinyin = PinyinHelper.getPinyin(nameCrl.text);
    if (pinyin.isEmpty) return;
    String tag = pinyin.split(" ").map((e) => e[0].toUpperCase()).join();
    codeCrl.text = tag;
  });

  return XDialog.showFormDialog(
      context: context,
      title: isEdit ? "编辑" : "新建目录",
      onOk: () {
        if (nameCrl.text.isEmpty) {
          ToastUtils.showMsg(msg: "请输入名称");
        } else if (codeCrl.text.isEmpty) {
          ToastUtils.showMsg(msg: "请输入代码");
        } else if (remarkCrl.text.isEmpty) {
          ToastUtils.showMsg(msg: "请输入备注信息");
        } else {
          if (onCreate != null) {
            onCreate(nameCrl.text, codeCrl.text, remarkCrl.text);
          }
          Navigator.pop(context);
        }
      },
      children: [
        XTextField.input(
            title: "名称",
            controller: nameCrl,
            required: true,
            // maxLine: 1,
            // textStyle: XFonts.size22Black0,
            hint: "请输入"),
        XTextField.input(
          title: "代码",
          controller: codeCrl,
          required: true,
          hint: "请输入",
          // showLine: true,
          // required: true,
          // maxLine: 1,
          // textStyle: XFonts.size22Black0
        ),
        XTextField.input(
          title: "备注信息",
          controller: remarkCrl,
          hint: "请输入",
          required: true,
          // showLine: true,
          // required: true,
          // maxLine: 5,
          // textStyle: XFonts.size22Black0
        )
      ]);
  // showDialog(
  //   context: context,
  //   builder: (context) {
  //     return Center(
  //       child: Material(
  //         child: Container(
  //             width: UIConfig.screenWidth - 32,
  //             padding: const EdgeInsets.all(16),
  //             child: SingleChildScrollView(
  //               child: StatefulBuilder(builder: (context, state) {
  //                 return SizedBox(
  //                   child: Column(
  //                     mainAxisSize: MainAxisSize.min,
  //                     children: [
  //                       CommonWidget.commonHeadInfoWidget(
  //                           isEdit ? "编辑" : "新建目录"),
  //                       CommonWidget.commonTextTile("名称", '',
  //                           controller: nameCrl,
  //                           showLine: true,
  //                           required: true,
  //                           maxLine: 1,
  //                           hint: "请输入",
  //                           textStyle: XFonts.size22Black0),
  //                       CommonWidget.commonTextTile("代码", '',
  //                           controller: codeCrl,
  //                           showLine: true,
  //                           required: true,
  //                           hint: "请输入",
  //                           maxLine: 1,
  //                           textStyle: XFonts.size22Black0),
  //                       CommonWidget.commonTextTile("备注信息", '',
  //                           controller: remarkCrl,
  //                           showLine: true,
  //                           required: true,
  //                           hint: "请输入",
  //                           maxLine: 5,
  //                           textStyle: XFonts.size22Black0),
  //                       CommonWidget.commonMultipleSubmitWidget(onTap1: () {
  //                         Navigator.pop(context);
  //                       }, onTap2: () {
  //                         if (nameCrl.text.isEmpty) {
  //                           ToastUtils.showMsg(msg: "请输入名称");
  //                         } else if (codeCrl.text.isEmpty) {
  //                           ToastUtils.showMsg(msg: "请输入代码");
  //                         } else if (remarkCrl.text.isEmpty) {
  //                           ToastUtils.showMsg(msg: "请输入备注信息");
  //                         } else {
  //                           if (onCreate != null) {
  //                             onCreate(
  //                                 nameCrl.text, codeCrl.text, remarkCrl.text);
  //                           }
  //                           Navigator.pop(context);
  //                         }
  //                       }),
  //                     ],
  //                   ),
  //                 );
  //               }),
  //             )),
  //       ),
  //     );
  //   },
  //   useSafeArea: true,
  // );
}
